/**
 * 查询结果分享服务层
 */

// 模拟查询结果数据
const mockQueryResults = [
  {
    eventId: 'EMG-2025-0001',
    eventName: '市中心化工厂泄漏事故',
    eventType: '重大',
    eventTime: '2025-11-05 08:30',
    location: '江北区工业园区化工厂',
    affectedArea: '周边半径2公里范围内',
    status: '处置中',
    description: '江北区工业园区某化工厂发生危险化学品泄漏事故，泄漏物质为氨气，现场已疏散周边居民约500人，应急处置队伍正在进行封闭处理。目前风向偏东，空气质量监测显示污染物浓度在可控范围内。',
    measures: [
      '立即启动应急预案，疏散周边居民',
      '设置警戒线，禁止无关人员进入',
      '调集专业应急处置队伍进行堵漏作业',
      '持续监测空气质量和泄漏物扩散情况',
      '协调医疗机构做好救治准备'
    ],
    responsiblePerson: '应急指挥长 王建国',
    contactPhone: '138-0000-1001'
  },
  {
    eventId: 'EMG-2025-0002',
    eventName: '南山区森林火灾',
    eventType: '较大',
    eventTime: '2025-11-04 14:20',
    location: '南山区白云山林区',
    affectedArea: '森林面积约300亩',
    status: '已控制',
    description: '南山区白云山林区发生森林火灾，过火面积约300亩。火灾发生后，立即调集森林消防队伍200余人参与扑救，出动消防车辆15台、直升机2架。经过8小时奋战，火势已得到有效控制，目前正在进行清理和监护工作。',
    measures: [
      '紧急调集森林消防队伍和装备',
      '使用直升机进行空中洒水灭火',
      '开设防火隔离带阻止火势蔓延',
      '疏散周边村民至安全区域',
      '24小时值守防止复燃'
    ],
    responsiblePerson: '森林防火指挥 赵卫东',
    contactPhone: '138-0000-1002'
  },
  {
    eventId: 'EMG-2025-0003',
    eventName: '东区地铁站突发停电',
    eventType: '一般',
    eventTime: '2025-11-05 07:15',
    location: '东区人民广场地铁站',
    affectedArea: '3条地铁线路受影响',
    status: '已结束',
    description: '早高峰期间东区人民广场地铁站突发停电事故，导致3条地铁线路暂时停运。站内滞留乘客约2000人。应急照明系统启动，工作人员及时引导乘客有序疏散。经抢修，电力于30分钟后恢复，地铁服务陆续恢复正常。',
    measures: [
      '启动应急照明系统',
      '组织工作人员引导乘客有序疏散',
      '紧急调派电力抢修队伍',
      '协调公交加密班次分流乘客',
      '及时发布运行信息告知市民'
    ],
    responsiblePerson: '交通应急协调员 孙艳华',
    contactPhone: '138-0000-1003'
  },
  {
    eventId: 'EMG-2025-0004',
    eventName: '西湖区暴雨内涝',
    eventType: '较大',
    eventTime: '2025-11-03 16:00',
    location: '西湖区老城区多处路段',
    affectedArea: '10余条道路积水严重',
    status: '已控制',
    description: '西湖区遭遇短时强降雨，1小时降雨量达80毫米，导致老城区多处低洼路段严重积水，最深处达50厘米。部分车辆被困，约100名群众需要转移。应急排涝队伍出动20台抽水设备进行抢排，消防救援队伍营救被困人员。',
    measures: [
      '启动防汛应急响应',
      '调集抽水设备进行应急排涝',
      '营救被困车辆和人员',
      '实施交通管制，引导车辆绕行',
      '安置转移群众，提供临时住所'
    ],
    responsiblePerson: '防汛指挥 周明远',
    contactPhone: '138-0000-1004'
  },
  {
    eventId: 'EMG-2025-0005',
    eventName: '北区食品安全事件',
    eventType: '一般',
    eventTime: '2025-11-02 12:30',
    location: '北区某学校食堂',
    affectedArea: '学校师生约500人',
    status: '待处理',
    description: '北区某中学食堂发生疑似食物中毒事件，约30名学生出现腹痛、呕吐等症状。事件发生后，立即停止食堂供餐，封存可疑食品样本送检，患病学生已送医院观察治疗。卫生部门介入调查，初步怀疑为食材存储不当导致。',
    measures: [
      '立即停止食堂供餐运营',
      '封存可疑食品并送检',
      '组织患病学生就医治疗',
      '开展食品安全专项检查',
      '追溯食材来源和加工过程'
    ],
    responsiblePerson: '卫生应急专员 陈丽娟',
    contactPhone: '138-0000-1005'
  }
];

// 模拟团队成员数据
const mockTeamMembers = [
  {
    id: 1,
    name: '王建国',
    role: '应急指挥长',
    department: '应急指挥中心',
    phone: '138-0000-1001',
    email: 'wangjianguo@emergency.gov',
    color: '#409EFF'
  },
  {
    id: 2,
    name: '赵卫东',
    role: '森林防火指挥',
    department: '消防救援队',
    phone: '138-0000-1002',
    email: 'zhaoweidong@emergency.gov',
    color: '#67C23A'
  },
  {
    id: 3,
    name: '孙艳华',
    role: '交通应急协调员',
    department: '交通运输局',
    phone: '138-0000-1003',
    email: 'sunyanhua@emergency.gov',
    color: '#E6A23C'
  },
  {
    id: 4,
    name: '周明远',
    role: '防汛指挥',
    department: '水利局',
    phone: '138-0000-1004',
    email: 'zoumingyuan@emergency.gov',
    color: '#F56C6C'
  },
  {
    id: 5,
    name: '陈丽娟',
    role: '卫生应急专员',
    department: '卫生健康局',
    phone: '138-0000-1005',
    email: 'chenlijuan@emergency.gov',
    color: '#909399'
  },
  {
    id: 6,
    name: '吴志强',
    role: '应急通讯专员',
    department: '应急指挥中心',
    phone: '138-0000-1006',
    email: 'wuzhiqiang@emergency.gov',
    color: '#409EFF'
  },
  {
    id: 7,
    name: '刘芳芳',
    role: '物资调度员',
    department: '应急物资储备中心',
    phone: '138-0000-1007',
    email: 'liufangfang@emergency.gov',
    color: '#67C23A'
  },
  {
    id: 8,
    name: '马晓东',
    role: '技术支持专员',
    department: '信息技术部',
    phone: '138-0000-1008',
    email: 'maxiaodong@emergency.gov',
    color: '#E6A23C'
  },
  {
    id: 9,
    name: '郑海燕',
    role: '医疗救护组长',
    department: '医疗救护队',
    phone: '138-0000-1009',
    email: 'zhenghaiyan@emergency.gov',
    color: '#F56C6C'
  },
  {
    id: 10,
    name: '冯建华',
    role: '后勤保障组长',
    department: '后勤保障部',
    phone: '138-0000-1010',
    email: 'fengjianhua@emergency.gov',
    color: '#909399'
  }
];

// 模拟分享历史数据
const mockShareHistory = [
  {
    id: 1,
    eventName: '市中心化工厂泄漏事故',
    method: 'team',
    recipients: ['王建国', '赵卫东', '孙艳华'],
    shareTime: '2025-11-05 09:15',
    status: '已送达'
  },
  {
    id: 2,
    eventName: '南山区森林火灾',
    method: 'email',
    recipients: ['应急指挥中心', '消防救援队'],
    shareTime: '2025-11-04 15:30',
    status: '已送达'
  },
  {
    id: 3,
    eventName: '东区地铁站突发停电',
    method: 'link',
    recipients: ['已生成链接'],
    shareTime: '2025-11-05 07:45',
    status: '已送达'
  },
  {
    id: 4,
    eventName: '西湖区暴雨内涝',
    method: 'text',
    recipients: ['文本已复制'],
    shareTime: '2025-11-03 16:30',
    status: '已送达'
  },
  {
    id: 5,
    eventName: '北区食品安全事件',
    method: 'team',
    recipients: ['陈丽娟', '郑海燕'],
    shareTime: '2025-11-02 13:00',
    status: '已送达'
  },
  {
    id: 6,
    eventName: '市中心化工厂泄漏事故',
    method: 'email',
    recipients: ['环保局', '卫生健康局'],
    shareTime: '2025-11-05 08:45',
    status: '发送中'
  }
];

/**
 * 获取查询结果列表
 */
export function getQueryResults() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockQueryResults]);
    }, 500);
  });
}

/**
 * 生成分享链接
 */
export function generateShareLink(result) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const baseUrl = 'https://emergency.gov.cn/share';
      const token = Math.random().toString(36).substr(2, 16);
      const link = `${baseUrl}/${result.eventId}?token=${token}&expires=7d`;
      resolve(link);
    }, 800);
  });
}

/**
 * 生成分享文本
 */
export function generateShareText(result) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const text = `【应急事件通报】

事件编号：${result.eventId}
事件名称：${result.eventName}
事件等级：${result.eventType}
发生时间：${result.eventTime}
发生地点：${result.location}
影响范围：${result.affectedArea}
当前状态：${result.status}

详细描述：
${result.description}

处置措施：
${result.measures.map((m, i) => `${i + 1}. ${m}`).join('\n')}

负责人员：${result.responsiblePerson}
联系电话：${result.contactPhone}

---
本信息由应急管理系统自动生成
生成时间：${new Date().toLocaleString('zh-CN')}`;
      
      resolve(text);
    }, 600);
  });
}

/**
 * 邮件分享
 */
export function sendEmailShare(data) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      const emails = data.to.split(',').map(e => e.trim());
      const invalidEmails = emails.filter(e => !emailRegex.test(e));
      
      if (invalidEmails.length > 0) {
        reject(new Error(`无效的邮箱地址: ${invalidEmails.join(', ')}`));
        return;
      }

      // 模拟发送成功
      const record = {
        id: Date.now(),
        eventName: data.result.eventName,
        method: 'email',
        recipients: emails,
        shareTime: new Date().toLocaleString('zh-CN'),
        status: '已送达'
      };
      
      // 添加到历史记录
      mockShareHistory.unshift(record);
      
      resolve({ success: true });
    }, 1000);
  });
}

/**
 * 分享给团队成员
 */
export function shareToTeamMembers(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const record = {
        id: Date.now(),
        eventName: data.result.eventName,
        method: 'team',
        recipients: data.members.map(m => m.name),
        shareTime: new Date().toLocaleString('zh-CN'),
        status: '已送达'
      };
      
      // 添加到历史记录
      mockShareHistory.unshift(record);
      
      resolve({ success: true });
    }, 1000);
  });
}

/**
 * 获取团队成员列表
 */
export function getTeamMembers() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockTeamMembers]);
    }, 500);
  });
}

/**
 * 获取分享历史记录
 */
export function getShareHistory() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockShareHistory]);
    }, 400);
  });
}

/**
 * 获取分享统计数据
 */
export function getShareStatistics() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        totalShares: 156,
        byMethod: {
          link: 45,
          text: 38,
          email: 42,
          team: 31
        },
        recentDays: [
          { date: '2025-10-30', count: 18 },
          { date: '2025-10-31', count: 22 },
          { date: '2025-11-01', count: 25 },
          { date: '2025-11-02', count: 19 },
          { date: '2025-11-03', count: 28 },
          { date: '2025-11-04', count: 24 },
          { date: '2025-11-05', count: 20 }
        ]
      });
    }, 500);
  });
}

/**
 * 删除分享记录
 */
export function deleteShareRecord(recordId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const index = mockShareHistory.findIndex(r => r.id === recordId);
      if (index > -1) {
        mockShareHistory.splice(index, 1);
      }
      resolve({ success: true });
    }, 300);
  });
}

/**
 * 重新分享
 */
export function reshareRecord(recordId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const record = mockShareHistory.find(r => r.id === recordId);
      if (record) {
        const newRecord = {
          ...record,
          id: Date.now(),
          shareTime: new Date().toLocaleString('zh-CN'),
          status: '已送达'
        };
        mockShareHistory.unshift(newRecord);
      }
      resolve({ success: true });
    }, 800);
  });
}

